package org.ztest.timer;

import java.util.Calendar;

public class Timer
{
	/**
	 * 计算现在时刻距离下一个指定日期(周、时、分、秒)最近的毫秒数
	 * @param dayOfWeek 周，参考{@link Calendar#DAY_OF_WEEK}
	 * @param hourOfDay 时
	 * @param minuteOfHour 分
	 * @param secondOfMinute 秒
	 * @return 距离下一个指定日期最近的毫秒数
	 */
	public long getNearestTriggerTime(int dayOfWeek, int hourOfDay, int minuteOfHour, int secondOfMinute)
	{
		Calendar now = Calendar.getInstance();
		int currentDayOfWeek = now.get(Calendar.DAY_OF_WEEK);
		int currentHour = now.get(Calendar.HOUR_OF_DAY);
		int currentMinute = now.get(Calendar.MINUTE);
		int currentSecond = now.get(Calendar.SECOND);
		
		boolean weekLater = false; // 是否要推迟一周
		if (dayOfWeek < currentDayOfWeek) {
			weekLater = true;
		} else if (dayOfWeek == currentDayOfWeek) {
			if (hourOfDay < currentHour) {
				weekLater = true;
			} else if (hourOfDay == currentHour) {
				if (minuteOfHour < currentMinute) {
					weekLater = true;
				} else if (minuteOfHour == currentMinute) {
					if (secondOfMinute < currentSecond) {
						weekLater = true;
					}
				}
			}
		}
		
		if (weekLater) {
			now.add(Calendar.WEEK_OF_YEAR, 1);
		}
		now.set(Calendar.DAY_OF_WEEK, dayOfWeek);
		now.set(Calendar.HOUR_OF_DAY, hourOfDay);
		now.set(Calendar.MINUTE, minuteOfHour);
		now.set(Calendar.SECOND, secondOfMinute);
		return now.getTimeInMillis();
	}
}
